package org.bagou.xiangs.framework_mvp.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.bagou.xiangs.framework_mvp.view.BaseView;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@SuppressLint({"NewApi", "LocalSuppress"})
public class MainMvpBaseActivity<P extends BasePresenter>
        extends AppCompatActivity implements BaseView {
    protected P mPresenter = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Type genericSuperclass = this.getClass().getGenericSuperclass();
//        // 判断类是否是泛型参数类型
//        if (genericSuperclass instanceof ParameterizedType) {
//            Type[] arguments = (ParameterizedType)genericSuperclass.getActualTypeArguments();
//            if (arguments != null && arguments[0] instanceof BasePresenter) {
//                try {
//                    mPresenter = (P)arguments[0].getClass().newInstance();
//                    mPresenter.attach(this); // 绑定view层对象到presenter层
//                } catch (Exception ex){
//                    ex.printStackTrace();
//                }
//            }
//        }
        // 获取当前具有泛型类型的Class
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        // 判断当前类型是否具有泛型类型参数
        if (genericSuperclass instanceof ParameterizedType) {
            // 具备泛型参数类型，然后获取泛型参数类型数组
            Type[] arguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments();
            try {
                try {
                    Class cls = (Class) arguments[0];
                    if (cls != null && cls.newInstance() instanceof BasePresenter) {
                        mPresenter = (P) cls.newInstance();
                        mPresenter.attach(this);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public boolean isActive() {
        return isFinishing() || isDestroyed();
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detach();
    }
}
